<script lang="ts" setup>
import { h, onMounted, ref, reactive } from 'vue';
import {
  showLoading,
  hideLoading,
  showToast,
  redirectTo,
  setNavigationBarTitle,
  getCurrentInstance,
} from '@tarojs/taro';
import { Plus as AppNutIconPlus } from '@nutui/icons-vue-taro';
import { Button } from '@nutui/nutui-taro';
import dayjs from 'dayjs';
import { LOGIN_APP } from '/@/api/modules/base/app-sys-user';
import { INSERT_CHANGE_ALLOCATION } from '/@/api/modules/equipment/asset-change-allocation';
import { formRules, state } from './state';
import { ASSET_DETAIL_QUERY } from '/@/api/modules/equipment/asset-manage';
/**
 * @description 当前路由信息
 */
const params = getCurrentInstance().router?.params as {
  /**
   * 页面类型
   * - default 设备调拨
   * - sign-in 设备签收
   */
  pageType?: 'sign-in' | 'default';
  assetId?: string;
};

const PAGE_TITLE = {
  default: '调拨',
  'sign-in': '签收',
};

const allocationEditFormRef = ref();

const formState = reactive<AssetChangeAllocationApi.InsertChangeAllocationReq>({
  changeTime: '',
  deptId: '',
  deptName: '',
  allocationDeptId: '',
  allocationDeptName: '',
  userId: '',
  userName: '',
  signUserId: '',
  signUserName: '',
  remark: '',
  assetList: [],
});

/**
 * @function 确认提交
 */
function submit() {
  allocationEditFormRef.value.validate().then(({ valid }) => {
    if (!valid) return;

    showLoading({ title: '加载中...' });
    INSERT_CHANGE_ALLOCATION(formState).then((res) => {
      hideLoading();
      showToast({
        title: res.comResp.msg || res.comResp.tip || '',
        icon: 'success',
        success: () => {
          setTimeout(() => {
            redirectTo({ url: `/pages/asset-change/allocation-detail/index?id=${res.changeId}` });
          }, 2000);
        },
      });
    });
  });
}

onMounted(() => {
  LOGIN_APP({}).then((res) => {
    formState.userId = res.sysUserDto.id;
    formState.userName = res.sysUserDto.name;
  });

  if (params.assetId) {
    ASSET_DETAIL_QUERY({ ids: [params.assetId] }).then((res) => {
      formState.assetList.push({
        assetId: res.assetInfo?.id,
        assetName: res.assetInfo?.assetName,
        assetCode: res.assetInfo?.assetCode,
        assetDeptId: res.assetInfo?.organizationId,
        assetDeptName: res.assetInfo?.organizationName,
        assetOldStatus: res.assetInfo?.status,
        render: () => {
          return h(
            Button,
            {
              plain: true,
              size: 'mini',
              type: 'danger',
              onClick: () => {
                formState.assetList.splice(
                  formState.assetList.findIndex((item) => {
                    return item.assetId === res.assetInfo?.id;
                  }),
                  1,
                );
              },
            },
            '删除',
          );
        },
      });
    });
  }

  setNavigationBarTitle({
    title: `设备${PAGE_TITLE[params.pageType || 'default']}`,
  });
});
</script>

<template>
  <view class="asset-allocation-edit app-page--1">
    <app-navbar :title="`设备${PAGE_TITLE[params.pageType || 'default']}`" />
    <nut-tabs
      class="asset-allocation-edit__tabs"
      model-value="push"
      @click="
        ({ paneKey }) => {
          if (paneKey === 'record') {
            redirectTo({ url: '/pages/asset-change/allocation-list/index' });
          }
        }
      "
    >
      <nut-tab-pane :title="`新增${PAGE_TITLE[params.pageType || 'default']}`" pane-key="push" />
      <nut-tab-pane :title="`${PAGE_TITLE[params.pageType || 'default']}列表`" pane-key="record" />
    </nut-tabs>
    <scroll-view class="app-page__wrapper" :scroll-y="true" :lower-threshold="100">
      <view class="asset-allocation-edit__wrapper">
        <nut-form
          :model-value="formState"
          :rules="formRules"
          class="asset-allocation-edit__form"
          ref="allocationEditFormRef"
        >
          <nut-form-item
            required
            prop="changeTime"
            label="调拨时间"
            label-align="left"
            error-message-align="left"
          >
            <nut-input
              :model-value="
                formState.changeTime ? dayjs(Number(formState.changeTime)).format('YYYY/MM/DD') : ''
              "
              placeholder="请选择调拨时间"
              :border="false"
              readonly
              input-align="right"
              @click-input="state.changeTimeCalendarIsShow = !state.changeTimeCalendarIsShow"
            />
          </nut-form-item>
          <nut-form-item
            required
            prop="deptId"
            label="调出部门"
            label-align="left"
            error-message-align="left"
          >
            <nut-input
              :model-value="formState.deptName"
              placeholder="请选择调出部门"
              :border="false"
              readonly
              input-align="right"
              @click-input="state.deptCascaderIsShow = !state.deptCascaderIsShow"
            />
          </nut-form-item>
          <nut-form-item
            required
            prop="allocationDeptId"
            label="调入部门"
            label-align="left"
            error-message-align="left"
          >
            <nut-input
              :model-value="formState.allocationDeptName"
              placeholder="请选择调入部门"
              :border="false"
              readonly
              input-align="right"
              @click-input="
                state.allocationDeptCascaderIsShow = !state.allocationDeptCascaderIsShow
              "
            />
          </nut-form-item>
          <nut-form-item
            required
            prop="signUserId"
            label="签收人"
            label-align="left"
            error-message-align="left"
          >
            <nut-input
              :model-value="formState.signUserName"
              placeholder="请选择签收人"
              :border="false"
              readonly
              input-align="right"
              @click-input="state.signUserPopupIsShow = !state.signUserPopupIsShow"
            />
          </nut-form-item>
          <nut-form-item label="备注信息" label-align="left" error-message-align="left">
            <nut-textarea
              v-model="formState.remark"
              placeholder="请输入备注"
              rows="4"
              limit-show
              text-align="right"
              max-length="200"
            />
          </nut-form-item>

          <nut-form-item
            required
            prop="assetList"
            label-width="0"
            label-align="left"
            error-message-align="left"
          >
            <nut-table
              class="asset-allocation-edit__table"
              bordered
              striped
              :columns="[
                { title: '设备编号', key: 'assetCode' },
                { title: '设备名称', key: 'assetName' },
                { title: '所属部门', key: 'assetDeptName' },
                { title: '操作', key: 'render' },
              ]"
              :data="formState.assetList"
            />
            <nut-button
              block
              plain
              shape="round"
              type="info"
              @click="
                () => {
                  if (!formState.deptId) {
                    showToast({
                      title: '请新增调出部门！',
                      icon: 'error',
                    });

                    return;
                  }
                  state.appAssetListPopupIsShow = !state.appAssetListPopupIsShow;
                }
              "
            >
              <template #icon>
                <app-nut-icon-plus />
              </template>
              <text>添加设备</text>
            </nut-button>
          </nut-form-item>
        </nut-form>
      </view>
    </scroll-view>

    <view class="asset-allocation-edit__footer">
      <nut-button block type="info" @click="submit">
        <text>提交</text>
      </nut-button>
    </view>

    <app-organ-cascader
      title="调出部门"
      v-model="state.deptCascaderIsShow"
      @on-selected="(_organIds: string[], organs: AppCascaderOrganDto[]) => {
        formState.deptId = organs[organs.length - 1].value;
        formState.deptName = organs[organs.length - 1].text;
      }"
    />

    <app-organ-cascader
      title="调入部门"
      v-model="state.allocationDeptCascaderIsShow"
      @on-selected="(_organIds: string[], organs: AppCascaderOrganDto[]) => {
        formState.allocationDeptId = organs[organs.length - 1].value;
        formState.allocationDeptName = organs[organs.length - 1].text;
      }"
    />

    <nut-calendar
      v-model:visible="state.changeTimeCalendarIsShow"
      :start-date="dayjs().format('YYYY-MM-DD')"
      :default-value="dayjs(formState.changeTime).format('YYYY-MM-DD')"
      @choose="(date: string | string[]) => {
        formState.changeTime = dayjs(date[3]).valueOf().toString();
      }"
    />
    <app-user-list-popup
      v-model="state.signUserPopupIsShow"
      title="签收人"
      :organId="formState.allocationDeptId"
      :organ="{ value: formState.allocationDeptId, text: formState.allocationDeptName }"
      @on-selected="(user: AppSysUser.Dto) => {
        formState.signUserName = user.name;
        formState.signUserId = user.id;
      }"
    />
    <app-asset-list-popup
      v-model="state.appAssetListPopupIsShow"
      title="调拨设备"
      :options="{
        status: [2, 5, 6],
        assetInfo: {
          organizationId: formState.deptId,
        },
      }"
      @on-selected="(assetItem: AssetInfo.Dto) => {
        if (formState.assetList.findIndex((item) => { return item.assetId === assetItem.id }) >= 0) return;

        formState.assetList.push({
          assetId: assetItem.id,
          assetName: assetItem.assetName,
          assetCode: assetItem.assetCode,
          assetDeptId: assetItem.organizationId,
          assetDeptName: assetItem.organizationName,
          assetOldStatus: assetItem.status,
          render: () => {
            return h(Button, { plain: true, size: 'mini', type: 'danger', onClick: () => {
              formState.assetList.splice(formState.assetList.findIndex((item) => { return item.assetId === assetItem.id }), 1)
            } }, '删除');
          },
        })

        showToast({ title: '添加设备成功!', icon: 'success', duration: 1000 });
      }"
    />
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
